package com.wanglei.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wanglei.constants.SystemConstants;
import com.wanglei.domain.entity.Menu;
import com.wanglei.service.MenuService;
import com.wanglei.mapper.MenuMapper;
import com.wanglei.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
* @author MrWang
* @description 针对表【sys_menu(菜单权限表)】的数据库操作Service实现
* @createDate 2023-07-03 13:48:28
*/
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu>
    implements MenuService{

    @Autowired
    private MenuMapper menuMapper;

    @Override
    public List<String> selectPermsByUserId(Long id) {
        //如果是管理员，返回所有的权限
        if(id==1){
            LambdaQueryWrapper<Menu> queryWrapper = new LambdaQueryWrapper<Menu>()
                    .eq(Menu::getStatus,SystemConstants.Menu_STATUS_NORMAL)
                    .in(Menu::getMenuType,"C","F");
            List<Menu> menus = menuMapper.selectList(queryWrapper);
            List<String> perms = menus.stream()
                    .map(Menu::getPerms)
                    .collect(Collectors.toList());
            return perms;
        }
        //否则返回所具有的权限
        return menuMapper.selectPermsByUserId(id);
    }

    //返回多级菜单
    @Override
    public List<Menu> selectRouterMenuTreeByUserId(Long userId) {
        List<Menu> menus = null;
        if (SecurityUtils.isAdmin()){//超级管理员 获取所有菜单
            menus = menuMapper.selectAllRouterMenu();
        }else {//其他用户 获取对应userid的菜单
            menus = menuMapper.selectRouterMenuTreeByUserId(userId);
        }

        //构建tree
        //先找出第一层的菜单  然后去找他们的子菜单设置到children属性中
        List<Menu> menusTree = builderMenuTree(menus,0L);
        return menusTree;
    }

    private List<Menu> builderMenuTree(List<Menu> menus, Long parentId) {
        List<Menu> menuTree = menus.stream()
                .filter(menu -> menu.getParentId().equals(parentId))
                //注意:这里的set没有返回值 需要在Menu实体类上加@Accessors(chain = true)
                //chain = true的作用是使成员属性的set方法不再返回void，而是返回对象本身，从而实现链式赋值
                .map(menu -> menu.setChildren(getChildren(menu,menus)))
                .collect(Collectors.toList());
        return menuTree;
    }

    //递归
    private List<Menu> getChildren(Menu menu, List<Menu> menus) {
        List<Menu> childrenList = menus.stream()
                .filter(m -> m.getParentId().equals(menu.getId()))
                .map(m -> m.setChildren(getChildren(m,menus)))// set同上
                .collect(Collectors.toList());
        return childrenList;
    }
}




